<template>
  <div class="notification-channel">
    <!-- 渠道列表 -->
    <el-row :gutter="20">
      <el-col :span="8" v-for="channel in channels" :key="channel.code">
        <el-card class="channel-card" :class="{ 'is-disabled': !channel.enabled }">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-icon :size="24" :class="channel.icon">
                  <component :is="channel.icon" />
                </el-icon>
                <span class="channel-name">{{ channel.name }}</span>
              </div>
              <el-switch
                v-model="channel.enabled"
                @change="handleChannelStatusChange(channel)"
              />
            </div>
          </template>
          <div class="card-content">
            <div class="channel-status">
              <el-tag :type="getStatusType(channel.status)">
                {{ getStatusLabel(channel.status) }}
              </el-tag>
              <el-tooltip
                :content="channel.statusMessage"
                placement="top"
                :show-after="500"
              >
                <el-icon class="info-icon"><InfoFilled /></el-icon>
              </el-tooltip>
            </div>
            <div class="channel-stats">
              <div class="stat-item">
                <span class="label">今日发送</span>
                <span class="value">{{ channel.stats.todayCount }}</span>
                <span class="unit">/ {{ channel.stats.todayLimit }}</span>
              </div>
              <div class="stat-item">
                <span class="label">本月发送</span>
                <span class="value">{{ channel.stats.monthCount }}</span>
                <span class="unit">/ {{ channel.stats.monthLimit }}</span>
              </div>
              <div class="stat-item">
                <span class="label">成功率</span>
                <span class="value">{{ channel.stats.successRate }}%</span>
              </div>
            </div>
            <div class="channel-actions">
              <el-button
                type="primary"
                link
                @click="handleConfig(channel)"
              >配置</el-button>
              <el-button
                type="primary"
                link
                @click="handleTest(channel)"
              >测试</el-button>
              <el-button
                type="primary"
                link
                @click="handleQuota(channel)"
              >配额</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 渠道配置对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      :title="`${currentChannel?.name}配置`"
      width="600px"
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        label-width="120px"
      >
        <template v-if="currentChannel?.code === 'email'">
          <el-form-item label="SMTP服务器" prop="smtp.host">
            <el-input v-model="configForm.smtp.host" placeholder="请输入SMTP服务器地址" />
          </el-form-item>
          <el-form-item label="SMTP端口" prop="smtp.port">
            <el-input-number v-model="configForm.smtp.port" :min="1" :max="65535" />
          </el-form-item>
          <el-form-item label="加密方式" prop="smtp.encryption">
            <el-select v-model="configForm.smtp.encryption">
              <el-option label="无" value="none" />
              <el-option label="SSL" value="ssl" />
              <el-option label="TLS" value="tls" />
            </el-select>
          </el-form-item>
          <el-form-item label="发件人邮箱" prop="smtp.username">
            <el-input v-model="configForm.smtp.username" placeholder="请输入发件人邮箱" />
          </el-form-item>
          <el-form-item label="邮箱密码" prop="smtp.password">
            <el-input
              v-model="configForm.smtp.password"
              type="password"
              placeholder="请输入邮箱密码或授权码"
              show-password
            />
          </el-form-item>
          <el-form-item label="发件人名称" prop="smtp.sender">
            <el-input v-model="configForm.smtp.sender" placeholder="请输入发件人名称" />
          </el-form-item>
        </template>

        <template v-if="currentChannel?.code === 'sms'">
          <el-form-item label="服务商" prop="sms.provider">
            <el-select v-model="configForm.sms.provider">
              <el-option label="阿里云" value="aliyun" />
              <el-option label="腾讯云" value="tencent" />
              <el-option label="华为云" value="huawei" />
            </el-select>
          </el-form-item>
          <el-form-item label="AccessKey" prop="sms.accessKey">
            <el-input v-model="configForm.sms.accessKey" placeholder="请输入AccessKey" />
          </el-form-item>
          <el-form-item label="AccessSecret" prop="sms.accessSecret">
            <el-input
              v-model="configForm.sms.accessSecret"
              type="password"
              placeholder="请输入AccessSecret"
              show-password
            />
          </el-form-item>
          <el-form-item label="签名" prop="sms.sign">
            <el-input v-model="configForm.sms.sign" placeholder="请输入短信签名" />
          </el-form-item>
        </template>

        <template v-if="currentChannel?.code === 'wecom'">
          <el-form-item label="企业ID" prop="wecom.corpId">
            <el-input v-model="configForm.wecom.corpId" placeholder="请输入企业ID" />
          </el-form-item>
          <el-form-item label="应用ID" prop="wecom.agentId">
            <el-input v-model="configForm.wecom.agentId" placeholder="请输入应用ID" />
          </el-form-item>
          <el-form-item label="应用密钥" prop="wecom.secret">
            <el-input
              v-model="configForm.wecom.secret"
              type="password"
              placeholder="请输入应用密钥"
              show-password
            />
          </el-form-item>
        </template>

        <template v-if="currentChannel?.code === 'dingtalk'">
          <el-form-item label="应用类型" prop="dingtalk.type">
            <el-radio-group v-model="configForm.dingtalk.type">
              <el-radio label="app">企业内部应用</el-radio>
              <el-radio label="robot">自定义机器人</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="configForm.dingtalk.type === 'app'">
            <el-form-item label="应用Key" prop="dingtalk.appKey">
              <el-input v-model="configForm.dingtalk.appKey" placeholder="请输入应用Key" />
            </el-form-item>
            <el-form-item label="应用Secret" prop="dingtalk.appSecret">
              <el-input
                v-model="configForm.dingtalk.appSecret"
                type="password"
                placeholder="请输入应用Secret"
                show-password
              />
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="Webhook" prop="dingtalk.webhook">
              <el-input v-model="configForm.dingtalk.webhook" placeholder="请输入Webhook地址" />
            </el-form-item>
            <el-form-item label="加签密钥" prop="dingtalk.secret">
              <el-input
                v-model="configForm.dingtalk.secret"
                type="password"
                placeholder="请输入加签密钥"
                show-password
              />
            </el-form-item>
          </template>
        </template>

        <template v-if="currentChannel?.code === 'feishu'">
          <el-form-item label="应用类型" prop="feishu.type">
            <el-radio-group v-model="configForm.feishu.type">
              <el-radio label="app">企业自建应用</el-radio>
              <el-radio label="robot">自定义机器人</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="configForm.feishu.type === 'app'">
            <el-form-item label="应用ID" prop="feishu.appId">
              <el-input v-model="configForm.feishu.appId" placeholder="请输入应用ID" />
            </el-form-item>
            <el-form-item label="应用密钥" prop="feishu.appSecret">
              <el-input
                v-model="configForm.feishu.appSecret"
                type="password"
                placeholder="请输入应用密钥"
                show-password
              />
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="Webhook" prop="feishu.webhook">
              <el-input v-model="configForm.feishu.webhook" placeholder="请输入Webhook地址" />
            </el-form-item>
            <el-form-item label="签名密钥" prop="feishu.secret">
              <el-input
                v-model="configForm.feishu.secret"
                type="password"
                placeholder="请输入签名密钥"
                show-password
              />
            </el-form-item>
          </template>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="configDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveConfig" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 测试对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      :title="`测试${currentChannel?.name}`"
      width="500px"
    >
      <el-form
        ref="testFormRef"
        :model="testForm"
        :rules="testRules"
        label-width="100px"
      >
        <template v-if="currentChannel?.code === 'email'">
          <el-form-item label="收件人" prop="email.to">
            <el-input v-model="testForm.email.to" placeholder="请输入收件人邮箱" />
          </el-form-item>
          <el-form-item label="主题" prop="email.subject">
            <el-input v-model="testForm.email.subject" placeholder="请输入邮件主题" />
          </el-form-item>
          <el-form-item label="内容" prop="email.content">
            <el-input
              v-model="testForm.email.content"
              type="textarea"
              :rows="4"
              placeholder="请输入邮件内容"
            />
          </el-form-item>
        </template>

        <template v-if="currentChannel?.code === 'sms'">
          <el-form-item label="手机号" prop="sms.phone">
            <el-input v-model="testForm.sms.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="模板" prop="sms.template">
            <el-select v-model="testForm.sms.template" placeholder="请选择短信模板">
              <el-option
                v-for="template in smsTemplates"
                :key="template.code"
                :label="template.name"
                :value="template.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-for="(param, index) in testForm.sms.params"
            :key="index"
            :label="param.name"
            :prop="`sms.params.${index}.value`"
          >
            <el-input
              v-model="param.value"
              :placeholder="`请输入${param.name}`"
            />
          </el-form-item>
        </template>

        <template v-if="['wecom', 'dingtalk', 'feishu'].includes(currentChannel?.code)">
          <el-form-item label="接收人" prop="receiver">
            <el-select
              v-model="testForm.receiver"
              :placeholder="请选择接收人"
              filterable
              remote
              :remote-method="searchUsers"
              :loading="searching"
            >
              <el-option
                v-for="user in userOptions"
                :key="user.id"
                :label="user.name"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="消息类型" prop="messageType">
            <el-radio-group v-model="testForm.messageType">
              <el-radio label="text">文本消息</el-radio>
              <el-radio label="markdown">Markdown</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="消息内容" prop="content">
            <el-input
              v-if="testForm.messageType === 'text'"
              v-model="testForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入消息内容"
            />
            <el-input
              v-else
              v-model="testForm.content"
              type="textarea"
              :rows="6"
              placeholder="请输入Markdown格式的消息内容"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="testDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendTest" :loading="testing">
          发送测试
        </el-button>
      </template>
    </el-dialog>

    <!-- 配额管理对话框 -->
    <el-dialog
      v-model="quotaDialogVisible"
      :title="`${currentChannel?.name}配额管理`"
      width="600px"
    >
      <el-form
        ref="quotaFormRef"
        :model="quotaForm"
        :rules="quotaRules"
        label-width="120px"
      >
        <el-form-item label="每日限额" prop="dailyLimit">
          <el-input-number
            v-model="quotaForm.dailyLimit"
            :min="0"
            :step="100"
            style="width: 200px"
          />
          <span class="unit">条/天</span>
        </el-form-item>
        <el-form-item label="每月限额" prop="monthlyLimit">
          <el-input-number
            v-model="quotaForm.monthlyLimit"
            :min="0"
            :step="1000"
            style="width: 200px"
          />
          <span class="unit">条/月</span>
        </el-form-item>
        <el-form-item label="发送频率" prop="rateLimit">
          <el-input-number
            v-model="quotaForm.rateLimit.count"
            :min="1"
            style="width: 120px"
          />
          <span class="unit">条/</span>
          <el-input-number
            v-model="quotaForm.rateLimit.seconds"
            :min="1"
            style="width: 120px"
          />
          <span class="unit">秒</span>
        </el-form-item>
        <el-form-item label="超额处理" prop="exceedAction">
          <el-radio-group v-model="quotaForm.exceedAction">
            <el-radio label="reject">拒绝发送</el-radio>
            <el-radio label="queue">加入队列</el-radio>
            <el-radio label="notify">通知管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="quotaForm.exceedAction === 'notify'"
          label="通知方式"
          prop="notifyChannels"
        >
          <el-checkbox-group v-model="quotaForm.notifyChannels">
            <el-checkbox label="email">邮件通知</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="wecom">企业微信</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="quotaDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveQuota" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Message,
  Bell,
  ChatDotRound,
  Connection,
  Platform,
  InfoFilled
} from '@element-plus/icons-vue'
import {
  getChannelList,
  updateChannelStatus,
  getChannelConfig,
  updateChannelConfig,
  testChannel,
  getChannelQuota,
  updateChannelQuota,
  searchUsers,
  getSmsTemplates
} from '@/api/message'

// 渠道列表
const channels = ref([
  {
    code: 'email',
    name: '邮件通知',
    icon: 'Message',
    enabled: false,
    status: 'disabled',
    statusMessage: '',
    stats: {
      todayCount: 0,
      todayLimit: 1000,
      monthCount: 0,
      monthLimit: 30000,
      successRate: 0
    }
  },
  {
    code: 'sms',
    name: '短信通知',
    icon: 'Bell',
    enabled: false,
    status: 'disabled',
    statusMessage: '',
    stats: {
      todayCount: 0,
      todayLimit: 1000,
      monthCount: 0,
      monthLimit: 30000,
      successRate: 0
    }
  },
  {
    code: 'wecom',
    name: '企业微信',
    icon: 'ChatDotRound',
    enabled: false,
    status: 'disabled',
    statusMessage: '',
    stats: {
      todayCount: 0,
      todayLimit: 1000,
      monthCount: 0,
      monthLimit: 30000,
      successRate: 0
    }
  },
  {
    code: 'dingtalk',
    name: '钉钉通知',
    icon: 'Connection',
    enabled: false,
    status: 'disabled',
    statusMessage: '',
    stats: {
      todayCount: 0,
      todayLimit: 1000,
      monthCount: 0,
      monthLimit: 30000,
      successRate: 0
    }
  },
  {
    code: 'feishu',
    name: '飞书通知',
    icon: 'Platform',
    enabled: false,
    status: 'disabled',
    statusMessage: '',
    stats: {
      todayCount: 0,
      todayLimit: 1000,
      monthCount: 0,
      monthLimit: 30000,
      successRate: 0
    }
  }
])

// 对话框显示状态
const configDialogVisible = ref(false)
const testDialogVisible = ref(false)
const quotaDialogVisible = ref(false)

// 当前操作的渠道
const currentChannel = ref(null)

// 加载状态
const saving = ref(false)
const testing = ref(false)
const searching = ref(false)

// 配置表单
const configFormRef = ref(null)
const configForm = reactive({
  smtp: {
    host: '',
    port: 465,
    encryption: 'ssl',
    username: '',
    password: '',
    sender: ''
  },
  sms: {
    provider: '',
    accessKey: '',
    accessSecret: '',
    sign: ''
  },
  wecom: {
    corpId: '',
    agentId: '',
    secret: ''
  },
  dingtalk: {
    type: 'app',
    appKey: '',
    appSecret: '',
    webhook: '',
    secret: ''
  },
  feishu: {
    type: 'app',
    appId: '',
    appSecret: '',
    webhook: '',
    secret: ''
  }
})

// 测试表单
const testFormRef = ref(null)
const testForm = reactive({
  email: {
    to: '',
    subject: '',
    content: ''
  },
  sms: {
    phone: '',
    template: '',
    params: []
  },
  receiver: '',
  messageType: 'text',
  content: ''
})

// 配额表单
const quotaFormRef = ref(null)
const quotaForm = reactive({
  dailyLimit: 1000,
  monthlyLimit: 30000,
  rateLimit: {
    count: 10,
    seconds: 60
  },
  exceedAction: 'reject',
  notifyChannels: []
})

// 短信模板列表
const smsTemplates = ref([])

// 用户选项
const userOptions = ref([])

// 表单验证规则
const configRules = {
  'smtp.host': [{ required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }],
  'smtp.port': [{ required: true, message: '请输入SMTP端口', trigger: 'blur' }],
  'smtp.username': [{ required: true, message: '请输入发件人邮箱', trigger: 'blur' }],
  'smtp.password': [{ required: true, message: '请输入邮箱密码', trigger: 'blur' }],
  'sms.provider': [{ required: true, message: '请选择服务商', trigger: 'change' }],
  'sms.accessKey': [{ required: true, message: '请输入AccessKey', trigger: 'blur' }],
  'sms.accessSecret': [{ required: true, message: '请输入AccessSecret', trigger: 'blur' }],
  'wecom.corpId': [{ required: true, message: '请输入企业ID', trigger: 'blur' }],
  'wecom.agentId': [{ required: true, message: '请输入应用ID', trigger: 'blur' }],
  'wecom.secret': [{ required: true, message: '请输入应用密钥', trigger: 'blur' }]
}

const testRules = {
  'email.to': [{ required: true, message: '请输入收件人邮箱', trigger: 'blur' }],
  'email.subject': [{ required: true, message: '请输入邮件主题', trigger: 'blur' }],
  'email.content': [{ required: true, message: '请输入邮件内容', trigger: 'blur' }],
  'sms.phone': [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  'sms.template': [{ required: true, message: '请选择短信模板', trigger: 'change' }],
  receiver: [{ required: true, message: '请选择接收人', trigger: 'change' }],
  content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }]
}

const quotaRules = {
  dailyLimit: [{ required: true, message: '请输入每日限额', trigger: 'blur' }],
  monthlyLimit: [{ required: true, message: '请输入每月限额', trigger: 'blur' }],
  'rateLimit.count': [{ required: true, message: '请输入发送数量', trigger: 'blur' }],
  'rateLimit.seconds': [{ required: true, message: '请输入时间间隔', trigger: 'blur' }],
  exceedAction: [{ required: true, message: '请选择超额处理方式', trigger: 'change' }]
}

// 初始化数据
onMounted(async () => {
  await fetchChannelList()
})

// 获取渠道列表
const fetchChannelList = async () => {
  try {
    const res = await getChannelList()
    channels.value = channels.value.map(channel => {
      const data = res.data.find(item => item.code === channel.code)
      return data ? { ...channel, ...data } : channel
    })
  } catch (error) {
    console.error('获取渠道列表失败:', error)
    ElMessage.error('获取渠道列表失败')
  }
}

// 处理渠道状态变更
const handleChannelStatusChange = async (channel) => {
  try {
    await updateChannelStatus(channel.code, channel.enabled)
    ElMessage.success(`${channel.name}${channel.enabled ? '启用' : '禁用'}成功`)
    await fetchChannelList()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    channel.enabled = !channel.enabled
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    enabled: 'success',
    disabled: 'info',
    error: 'danger',
    testing: 'warning'
  }
  return typeMap[status] || ''
}

// 获取状态标签
const getStatusLabel = (status) => {
  const labelMap = {
    enabled: '正常',
    disabled: '已禁用',
    error: '异常',
    testing: '测试中'
  }
  return labelMap[status] || status
}

// 处理配置
const handleConfig = async (channel) => {
  currentChannel.value = channel
  try {
    const res = await getChannelConfig(channel.code)
    Object.assign(configForm, res.data)
    configDialogVisible.value = true
  } catch (error) {
    console.error('获取配置失败:', error)
    ElMessage.error('获取配置失败')
  }
}

// 保存配置
const saveConfig = async () => {
  if (!configFormRef.value) return
  
  try {
    await configFormRef.value.validate()
    saving.value = true
    
    await updateChannelConfig(currentChannel.value.code, configForm)
    ElMessage.success('保存成功')
    configDialogVisible.value = false
    await fetchChannelList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 处理测试
const handleTest = async (channel) => {
  currentChannel.value = channel
  
  if (channel.code === 'sms') {
    try {
      const res = await getSmsTemplates()
      smsTemplates.value = res.data
    } catch (error) {
      console.error('获取短信模板失败:', error)
      ElMessage.error('获取短信模板失败')
      return
    }
  }
  
  testDialogVisible.value = true
}

// 搜索用户
const searchUsers = async (query) => {
  if (!query) return
  
  searching.value = true
  try {
    const res = await searchUsers({ query })
    userOptions.value = res.data
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    searching.value = false
  }
}

// 发送测试
const sendTest = async () => {
  if (!testFormRef.value) return
  
  try {
    await testFormRef.value.validate()
    testing.value = true
    
    const data = {
      channel: currentChannel.value.code,
      ...testForm
    }
    await testChannel(data)
    ElMessage.success('发送成功')
    testDialogVisible.value = false
  } catch (error) {
    console.error('发送失败:', error)
    ElMessage.error(error.message || '发送失败')
  } finally {
    testing.value = false
  }
}

// 处理配额
const handleQuota = async (channel) => {
  currentChannel.value = channel
  try {
    const res = await getChannelQuota(channel.code)
    Object.assign(quotaForm, res.data)
    quotaDialogVisible.value = true
  } catch (error) {
    console.error('获取配额配置失败:', error)
    ElMessage.error('获取配额配置失败')
  }
}

// 保存配额
const saveQuota = async () => {
  if (!quotaFormRef.value) return
  
  try {
    await quotaFormRef.value.validate()
    saving.value = true
    
    await updateChannelQuota(currentChannel.value.code, quotaForm)
    ElMessage.success('保存成功')
    quotaDialogVisible.value = false
    await fetchChannelList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}
</script>

<style lang="scss" scoped>
.notification-channel {
  padding: 20px;

  .channel-card {
    margin-bottom: 20px;
    transition: all 0.3s;

    &.is-disabled {
      opacity: 0.6;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;

        .channel-name {
          font-size: 16px;
          font-weight: bold;
        }
      }
    }

    .card-content {
      .channel-status {
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        gap: 8px;

        .info-icon {
          font-size: 14px;
          color: #909399;
          cursor: help;
        }
      }

      .channel-stats {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        margin-bottom: 16px;

        .stat-item {
          text-align: center;

          .label {
            display: block;
            font-size: 12px;
            color: #909399;
            margin-bottom: 4px;
          }

          .value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
          }

          .unit {
            font-size: 12px;
            color: #909399;
            margin-left: 4px;
          }
        }
      }

      .channel-actions {
        display: flex;
        justify-content: center;
        gap: 16px;
      }
    }
  }

  .unit {
    margin-left: 8px;
    color: #909399;
  }
}
</style> 